package net.keebook.webapp.bean;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;

import net.keebook.webapp.dao.KeeBookDao;
import net.keebook.webapp.dao.UserDao;
import net.keebook.webapp.entity.KeeBook;
import net.keebook.webapp.entity.User;
import net.keebook.webapp.model.SessionModel;
import net.keebook.webapp.util.AccessRight;
import net.keebook.webapp.util.MessageBundle;
import net.keebook.webapp.util.Messages;


@ManagedBean
@RequestScoped
public class CreateKeeBookBean {
	private String keeBookName = MessageBundle.get().getString("createBook.defaultTitle");
	private String masterPassword = "";
	private Boolean passwordChecked;
	private String salt = UUID.randomUUID().toString();
	private SessionModel sessionModel;
	
	@Inject
	private KeeBookDao keeBookDao;
	
	@Inject
	private UserDao userDao;
	
	@PostConstruct
	public void init() {
		setSessionModel(SessionModel.getInstance(FacesContext.getCurrentInstance()));
	}
	
	public void create() throws IOException {
		KeeBook keeBook = new KeeBook();
		keeBook.setName(getKeeBookName());
		keeBook.setKeyphraseChecksum(getMasterPassword());
		keeBook.setSalt(getSalt());
		getKeeBookDao().store(keeBook);
		
		User user = getUserDao().get(getSessionModel().getUserId());
		getKeeBookDao().setAccessRight(user, keeBook, AccessRight.OWNER);
		
		getSessionModel().setKeeBookId(keeBook.getId());
		FacesContext.getCurrentInstance().getExternalContext().redirect("index.xhtml?msg="+Messages.KEYBOX_CREATED);
	}
	
	public List<KeeBook> getBoxes() {
		return getKeeBookDao().getList(getSessionModel().getUserId());
	}
	public KeeBookDao getKeeBookDao() {
		return keeBookDao;
	}
	public void setKeeBookDao(KeeBookDao keeBookDao) {
		this.keeBookDao = keeBookDao;
	}

	public String getMasterPassword() {
		return masterPassword;
	}

	public void setMasterPassword(String masterPassword) {
		this.masterPassword = masterPassword;
	}

	public String getKeeBookName() {
		return keeBookName;
	}

	public void setKeeBookName(String keeBookName) {
		this.keeBookName = keeBookName;
	}

	public String getSalt() {
		return salt;
	}

	public void setSalt(String salt) {
		this.salt = salt;
	}

	public SessionModel getSessionModel() {
		return sessionModel;
	}

	public void setSessionModel(SessionModel sessionModel) {
		this.sessionModel = sessionModel;
	}

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public Boolean getPasswordChecked() {
		return passwordChecked;
	}

	public void setPasswordChecked(Boolean passwordChecked) {
		this.passwordChecked = passwordChecked;
	}
}
